
PLUG.Platform = PLUG_PLATFORM_SERVER

PLUG.ClassName = "sv_datastorage"
PLUG.PrintName = "Serverside Data Storage"
PLUG.Author = "thomasfn"

PLUG.Hard = true

// We use a file in the data folder to indicate our storage method
local DataStorageMethodFile = "gmanage/datastorage.txt"
local ActivatedMethod = ""

function PLUG:GetDataStorageMethod()
	if (!file.Exists( DataStorageMethodFile )) then return "file" end
	local fl = file.Read( DataStorageMethodFile )
	if (fl == "") then return "file" end
	return fl
end

function PLUG:SetDataStorageMethod( method )
	file.Write( DataStorageMethodFile, method )
end

function PLUG:LoadDataStorageMethods()
	self.DataMethods = {}
	for _, v in pairs( file.FindInLua( "gmanage/plugs/datastorage/*.lua" ) ) do
		local filename = "gmanage/plugs/datastorage/" .. v
		DATA = {}
		include( filename )
		local name = DATA.InternalName or "base"
		self.DataMethods[ name ] = DATA
		DATA = nil
		Msg( "GManage: Loaded data storage method '" .. name .. "'!\n" )
	end
end

function PLUG:ActivateDataStorageMethod( id )
	if (!self.DataMethods) then return end
	local curmethod = self.DataMethods[ ActivatedMethod ]
	if (curmethod) then
		for metid, _ in pairs( curmethod ) do
			self[ metid ] = nil -- There had better not be any common key values...
		end
	end
	local newmethod = self.DataMethods[ id ]
	if (newmethod) then
		for metid, val in pairs( newmethod ) do
			self[ metid ] = val
		end
	end
	ActivatedMethod = id
	SetGlobalString( "gmanage_datstore", id )
	Msg( "GManage: Activated data storage method '" .. id .. "'!\n" )
end

function PLUG:InitDataStorage()
	plugs.Call( "LoadDataStorageMethods" )
	local method = plugs.Call( "GetDataStorageMethod" )
	plugs.Call( "ActivateDataStorageMethod", method )
end

function PLUG:ManifestDataStorageMethods()
	local tmp = {}
	for k, v in pairs( self.DataMethods ) do
		table.insert( tmp, k .. "," .. v.MethodName )
	end
	return table.concat( tmp, ";" )
end

function PLUG:DoConCommand( ply, com, args )
	if (com == "selectdatastoragemethod") then
		if (!ply:HasPriv( "manage_server" )) then return end
		if (!self.DataMethods) then self.DataMethods = {} end
		local methodname = args[1] or "file"
		local method = self.DataMethods[ methodname ]
		if (!method) then
			ply:PrintMessage( HUD_PRINTTALK, "That method is not valid!" )
			return true
		end
		plugs.Call( "SetDataStorageMethod", methodname )
		plugs.Call( "ActivateDataStorageMethod", methodname )
		return true
	end
	if (com == "getdatastoragemethods") then
		
	end
end